package com.eliza.security.service.impl;

import com.eliza.security.dao.UserDao;
import com.eliza.security.fronts.LoginModel;
import com.eliza.security.model.Permission;
import com.eliza.security.model.UserModel;
import com.eliza.security.service.UserService;
import com.eliza.security.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    /**
     * 根据用户名查询用户信息
     * @param userName
     * @return
     */
    @Override
    public UserModel getUserByName(String userName) {
        List<UserModel> userNames = userDao.getUserByName(userName);
        Assert.isTrue(userNames.size()==1,"没有查询到该用户!");
        return userNames.get(0);

    }

    /**
     * 根据用户id查询用户的权限
     * @param id
     * @return
     */
    @Override
    public List<Permission> getPermissionByUserId(Integer id) {
        return userDao.getPermissionByUserId(id);
    }

    /**
     * 登录验证，使用token
     * @param loginModel
     * @return
     */
    @Override
    public String login(LoginModel loginModel) {
        String userName = loginModel.getUserName();
        Assert.notNull(userName,"账号不能为空哦！");
        String password = loginModel.getPassword();
        Assert.notNull(password,"密码不能为空哦！");
        UserModel userByName = getUserByName(userName);//调用这个方法查询用户信息，需要用到密码，来匹配
        boolean matches = passwordEncoder.matches(password, userByName.getPassword());
        if (matches){//false就不进入，直接return null
            //todo..颁发token
            return jwtTokenUtil.generateToken(userByName);
        }
        return null;
    }
}
